import request from '@/api/request.js';
import config from '@/config/index.js'

// 获取
export const upload_token = () => {
	return request.get('/http/upload/token');
}

// 上传
export const upload_qiniup = (params) => {
	return request.post('https://upload-z1.qiniup.com', params);
}

export const creteFileName = (type) => {
	let _name = Math.random().toString(16).slice(2);
	_name += +new Date();
	if (type) {
		return _name + "." + type;
	}
	return _name;
}

export const uploadFile = async (file) => {
	let result = null;
	try {
		let {
			token
		} = await upload_token();

		let type = file.type.split('/')[1];
		let key = creteFileName(type);

		let formdata = new FormData();
		formdata.append("file", file);
		formdata.append("key", key);
		formdata.append("token", token);

		result = await upload_qiniup(formdata);
	}catch (error) {
		return Promise.reject(error)
	}




	return config.baseImgUrl + result.key
}
